//
//  SaleTitleView.m
//  SmallEasyLife
//
//  Created by qianfeng on 15/10/23.
//  Copyright © 2015年 GXK. All rights reserved.
//

#import "SaleTitleView.h"
#import "Masonry.h"

#define INDICATOR_HEIGHT 3.

@interface SaleTitleView ()

@property (nonatomic, weak) IBOutlet UIButton * leftButton;
@property (nonatomic, weak) IBOutlet UIButton * rightButton;

@property (nonatomic, strong) NSArray * buttonArray;
@property (nonatomic, strong) NSArray * indicatorArray;


@property (nonatomic, weak) UIView * indicatorMover;


@end

@implementation SaleTitleView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)awakeFromNib
{
    [self createUI];
}
- (void)createUI
{
    NSMutableArray * mBuArr = [[NSMutableArray alloc] init];
    [mBuArr addObject:self.leftButton];
    [mBuArr addObject:self.rightButton];
    self.buttonArray = mBuArr;
    
    NSMutableArray * mInArr = [[NSMutableArray alloc] init];
    
    for (NSInteger i =0 ; i < self.buttonArray.count ; ++i)
    {
        UIButton * button = self.buttonArray[i];
        
        UIView * indicator = [[UIView alloc] initWithFrame:CGRectZero];
        
        indicator.backgroundColor = [UIColor clearColor];
        
        [button addSubview:indicator];
        [self bringSubviewToFront:indicator];
        
        [indicator mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(button.mas_left);
            make.width.equalTo(button.mas_width);
            make.bottom.equalTo(button.mas_bottom);
            make.height.equalTo(@(INDICATOR_HEIGHT));
        }];
        [mInArr addObject:indicator];
    }
    self.indicatorArray = mInArr;
    _currentPage = NSNotFound;
    self.currentPage = 0;
    
    [self layoutIfNeeded];
}


- (UIView *)indicatorMover
{
    if (_indicatorMover == nil) {
        UIView * indicatorMover = [[UIView alloc] initWithFrame:CGRectZero];
        _indicatorMover = indicatorMover;
        [self addSubview:indicatorMover];
        
        indicatorMover.backgroundColor = [UIColor blackColor];
    }
    return _indicatorMover;
}

- (void)setCurrentPage:(NSInteger)currentPage
{
    if (_currentPage == currentPage) {
        return;
    }
    
    if (_currentPage > self.buttonArray.count) {
        _currentPage = 0;
    }
    
    UIButton * lastButton = self.buttonArray[_currentPage];
    lastButton.selected = NO;
    self.indicatorMover.frame = ((UIView *)self.indicatorArray[_currentPage]).frame;
    
    UIButton * currentButton = self.buttonArray[currentPage];
    currentButton.selected = YES;
     self.indicatorMover.frame = ((UIView *)self.indicatorArray[currentPage]).frame;
    [self bringSubviewToFront:self.indicatorMover];
    
    _currentPage = currentPage;
}



@end
